<template lang="pug">
div(class="default-create-form")
      el-form(@submit.native.prevent label-width="120px")
          template(v-for="(field,index) in config_copy.fields")
              el-form-item(:key="field.label" :label="field.label" v-show="!field.hide")
                  template(v-if="field.type === 'Number'")
                  template(v-else-if="field.type === 'Checkbox'")
                      <!--复选框-->
                      el-checkbox-group(v-model="field.val")
                          template(v-for="option in field.options")
                              el-checkbox(:key="option.label" :label="option.val") {{option.label}}
                  template(v-else-if="field.type === 'Radio'")
                      <!--单选框-->
                      template(v-for="option in field.options")
                          el-radio(:key="option.label" :label="option.val" v-model="field.val") {{option.label}}
                  template(v-else-if="field.type === 'Selection'")
                      <!--下拉选择框-->
                      SelectionField(v-model="field.val" :field="field")
                  template(v-else-if="field.type == 'Date'")
                      el-date-picker(v-model="field.value" type="date" placeholder="选择日期")
                  template(v-else-if="field.type == 'Datetime'")
                      el-date-picker(v-model="field.val" type="date" placeholder="选择日期")
                      el-time-select( v-model="field.time"  placeholder="选择时间" class="time-select")
                  template(v-else-if="field.type == 'Image'")
                       Upload(:field="field" :ref="field.fieldName" @uplod-fail="upload_fail")
                  template(v-else)
                      el-input(v-model="field.val" :disabled="field.readonly")
          template
              el-form-item(label=" ")
                  el-row
                      el-col(:span="12")
                          template(v-if="submiting")
                            el-button(type="primary" @click="submit") 提交中...
                          template(v-else)
                            el-button(type="primary" @click="submit") 提交
                          el-button(:disabled="submiting" @click="reset") 重置
                      el-col(:span="12" class="pull-right")
                          el-button(type="danger" :disabled="submiting" @click="close") 返回
</template>
<script>
import axios from "../../../plugins/axios";
import { Message } from "element-ui";
import util from "../../../libs/util";
import Upload from "./upload";
import { mapActions, mapGetters } from "vuex";

import SelectionField from "./components/selection-field";

export default {
  name: "simple-maintenace-creaate",
  components: { Upload, SelectionField },
  data() {
    return {
      submiting: false, // 提交中...

      config_copy: { action: "", fields: [] }
    };
  },
  props: {
    config: {
      type: Object,
      default: () => {
        return {
          fields: []
        };
      }
    }
  },
  computed: {
    imageFields() {
      let images = [];
      this.config_copy.fields.forEach(field => {
        if (field.type === "Image") images.push(field);
      });
      return images;
    },
    isEdit() {
      return this.$store.state.status.rightPart === "update";
    }
  },
  watch: {
    config() {
      this.config_copy = JSON.parse(JSON.stringify(this.config));
    }
  },
  methods: {
    submit() {
      if (this.imageFields.length == 0) {
        // 如果没有图片字段 执行
        this.doSubmit();
        return;
      }

      const vm = this;
      let promiseList = [];
      this.imageFields.forEach(field => {
        // _(¦3」∠)_ 条用提交按钮 要做成promise 实现全部上传完成出发下面的promise.all
        const promise = new Promise((resolve, reject) => {
          this.$refs[field.fieldName][0].submit(images => {
            if (images.length) {
              const image = images[0];
              field.val = image.id;
            }
            resolve();
          });
        });
        promiseList.push(promise);
      });

      this.submiting = true;
      Promise.all(promiseList)
        .then(() => vm.doSubmit())
        .then(() => (this.submiting = false));
    },

    doSubmit() {
      var data = this.toModel();

      const options = {
        url: this.config_copy.action,
        method: "post",
        data: data
      };

      this.submiting = true;
      axios(options)
        .then(res => {
          Message.success("保存成功");
          this.$emit("submit-success", res);
          if (!this.isEdit) this.reset();
        })
        .catch(err => Message.error(err.message))
        .then(t => (this.submiting = false));
    },

    toModel() {
      let model = {};
      this.config_copy.fields.forEach(field => {
        model[field.fieldName] = field.val;
      });
      return model;
    },

    close() {
      this.$store.dispatch("status/hideForm");
    },

    reset() {
      this.imageFields.forEach(field => {
        this.$refs[field.fieldName][0].clear();
      });
      this.config_copy = JSON.parse(JSON.stringify(this.config));
    },

    upload_fail() {
      this.submiting = false;
    }
  },
  created() {
    this.config_copy = JSON.parse(JSON.stringify(this.config));
  }
};
</script>
<style scoped lang="less">
.pull-right {
  text-align: right;
}
.time-select {
  width: 150px;
}
</style>
